﻿namespace S4sme.Tasks.Blog
{
    using System.Linq;

    using S4sme.Domain;
    using S4sme.Tasks.Blog.ViewModels;

    using SharpLite.Domain.DataInterfaces;

    /// <summary>
    /// Comments tasks
    /// </summary>
    public class CommentCudTasks : BaseEntityCudTasks<Comment, EditCommentViewModel>
    {
        private readonly IRepository<Comment> commentRepository;

        public CommentCudTasks(IRepository<Comment> commentRepository)
            : base(commentRepository)
        {
            this.commentRepository = commentRepository;
        }

        /// <summary>
        /// Basic view model factory which initializes lists for dropdowns and adds any security
        /// details to the view model (e.g., .MayAddAttachments) if appropriate.
        /// We can't use the CreateEditViewModel() from the base class because we need to add
        /// categories to the view model which will be shown in a dropdown list.
        /// </summary>
        /// <returns>
        /// The create edit view model.
        /// </returns>
        public override EditCommentViewModel CreateEditViewModel() 
        {
            var viewModel = base.CreateEditViewModel();

            // These will be displayed by the view to optionally select a parent comment
            viewModel.AvailableComments = this.commentRepository.GetAll().OrderBy(c => c.CreatedDate);

            return viewModel;
        }

        /// <summary>
        /// We need to replace the base class' version of this because we need to modify the comment before it gets passed to the view.
        /// </summary>
        /// <param name="comment">
        /// The comment.
        /// </param>
        /// <returns>
        /// The create edit view model.
        /// </returns>
        public override EditCommentViewModel CreateEditViewModel(Comment comment) 
        {
            var viewModel = this.CreateEditViewModel();
            viewModel.Comment = comment;

            // Don't allow a comment to have itself as a parent
            viewModel.AvailableComments = viewModel.AvailableComments.Where(c => !c.Equals(comment));

            return viewModel;
        }

        protected override void TransferFormValuesTo(Comment toUpdate, Comment fromForm)
        {
            toUpdate.IsApproved = fromForm.IsApproved;
            toUpdate.IsDeleted = fromForm.IsDeleted;
            toUpdate.IsSpam = fromForm.IsSpam;
        }
    }
}
